//
//  PicturePickerController.swift
//  照片选择器
//
//  Created by 晁岳山 on 15/10/26.
//  Copyright © 2015年 晁岳山. All rights reserved.
//

import UIKit

private let picturePickerCellId = "picturePickerCellId"
private let imageMaxCount = 9
class PicturePickerController: UICollectionViewController {
    //照片数组
    lazy var pictures = [UIImage]()
    //当前选中图片的索引
    private var currentIndex = 0
    // MARK: 构造方法 - PicturePickerController
    init() {
        let layout = PictureLayout()
        super.init(collectionViewLayout: layout)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        //注册cell
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: picturePickerCellId)
    }
    // MARK: 自定义layout（类中类）
    private class PictureLayout: UICollectionViewFlowLayout {
        override private func prepareLayout() {
            super.prepareLayout()
            let scale = UIScreen.mainScreen().scale
            let margin = 4 * scale
            let rowCount: CGFloat = 4
            let width = (collectionView!.bounds.width - (rowCount + 1) * margin) / rowCount
            itemSize = CGSizeMake(width, width)
            minimumInteritemSpacing = 0
            minimumLineSpacing = margin
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        }
    }

    
}
// MARK: UICollectionViewDataSource - 数据源方法
extension PicturePickerController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count + (pictures.count == imageMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(picturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        //设置代理
        cell.pictureDelegate = self
        return cell
    }
}
extension PicturePickerController: PicturePickerCellDelegate {
    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
       //访问相册
        
//        PhotoLibrary
//        Camera
//        SavedPhotosAlbum  三个参数的含义？？？
        //判断是否允许访问相册
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("不允许访问相册")
            return
        }
        //拿到当前选中的buuton的位置
        currentIndex = collectionView!.indexPathForCell(cell)!.item
        //进入相册
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
        
    }
    /// 删除按钮
   @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
        let indexPath = collectionView!.indexPathForCell(cell)!
        print(indexPath)
        if pictures.count < indexPath.item {
            return
        }
        pictures.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
//        //这样写有动画效果
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
    }
}
// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
//一旦实现了这个代理方法  就需要自己dismiss掉控制器
extension PicturePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //对图片进行处理  避免内存过大
        let scaleImage =  image.scaleToWidth(600)
        if currentIndex < pictures.count {
            pictures[currentIndex] = scaleImage
        }else {
            //添加到数组
            pictures.append(scaleImage)
        }
        //刷新数据
        collectionView?.reloadData()
        //一旦实现了这个代理方法  就需要自己dismiss掉控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
/// cell按钮点击事件的代理 传消息到控制器中
@objc  //如果定义的协议是私有的  那么定义的协议方法也是私有的  在实现方法的时候 @objc
private protocol PicturePickerCellDelegate: NSObjectProtocol {
     optional func picturePickerCellDidAdd(cell: PicturePickerCell)
     optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}

// MARK: 自定义cell
private class PicturePickerCell: UICollectionViewCell {
    
    //MARK: - 定义代理  设置代理的时候要用weak  swift中定义代理的方法
    weak var pictureDelegate: PicturePickerCellDelegate?
    
    private var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            //设置图片的填充模式(这个必须设置  要不然 长图片会被压缩变形)
            addButton.imageView?.contentMode = .ScaleAspectFill
            addButton.imageView?.clipsToBounds = true
//            if image == nil {
//                removeButton.hidden = true
//            }else{
//                removeButton.hidden = false
//            }
            removeButton.hidden = (image == nil )
        }
    }
    // MARK: 构造函数 - Cell
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: 设置界面
    private func setupUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        //设置自动布局
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addButton.snp_top)
            make.right.equalTo(addButton.snp_right)
        }
        //添加按钮点击事件
        addButton.addTarget(self, action: "addButtonClick", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removeButtonClick", forControlEvents: .TouchUpInside)
    }
    // MARK: 懒加载
    private lazy var addButton: UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
    // MARK: addButton removeButton 的按钮点击事件
    @objc private func addButtonClick() {
        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    @objc private func removeButtonClick() {
        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
}